import { Service } from 'egg';
import * as moment from 'moment';
import * as config from '../../config.json';
export default class BiReportMail extends Service {
  public async queryBiReport() {
    const { app } = this;
    const time =  moment().subtract(1, 'days').format('YYYY-MM-DD');
    const query = {
      create_time: time,
    };
    const options = {
      fields: {
        _id: 1,
        companyName: 1,
        name: 1,
      },
    };
    const obj: { success: boolean, data?: any } = {
      success: false,
    };
    let find;
    try {
      const accountArray =
        await app.commonDB.db().collection(app.constants.DB_BI_REPORT_COUNT)
          .find(query).toArray();
      if (accountArray.length === 0) {
        obj.success = false;
        return obj;
      }
      const queryMany = {
        _id: {
          $in: accountArray.map((v) => v.account),
        },
      };
      const data = await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_PLATFORM_ACCOUNT)
        .find(queryMany, options).toArray();
      if (data.length === 0) {
        obj.success = false;
        return obj;
      }
      for (const element of data) {
        find = accountArray.find((v) => element._id === v.account);
        if (find) {
          element.count = find.count;
        }
      }
      obj.success = true;
      obj.data = data;
      return obj;
    } catch (error) {
      this.ctx.result.success = false;
      this.ctx.logger.error('获取bi智能报表计数失败', error.message);
      return obj;
    }

  }

  public async addSendMail(query) {
    const { app } = this;
    const time = `${app.m7Utils.DateTime.getCurrentDate()} 8:00:00`;
    const address: any = config.bi_send_email_address;
    this.ctx.logger.info('address', address);
    const obj = {
      // toAddr: ['product@7moor.com'],
      toAddr: address,
      type: 'notify',
      ccAddr: [],
      status: 'undeal',
      warningTime: time,
      subject: '每天定时发送BiDemo访问次数',
      content: '',
      sendTime: time,
    };
    try {
      for (const element of query.data) {
        obj.content += `
        账户ID：${element._id}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        公司名称：${element.companyName}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        账户名称：${element.name}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        访问次数：${element.count}   <br>`;
      }
      const data = (await app.commonDB.db(app.constants.BILL).collection(app.constants.DB_BILL_SYSTEM_MAIL_SEND)
        .insertOne(obj)).ops;
      return data;
    } catch (error) {
      this.ctx.result.success = false;
      this.ctx.logger.error('统计邮件发送信息失败', error.message);
      return error.message;
    }
  }
}
